// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from 'vscode';
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed

const decorations: vscode.TextEditorDecorationType[] = [];
const workspaceConfig = vscode.workspace.getConfiguration(); // 获取插件相关的所有工作区配置
const defaultColor = "lightblue";
const highlightColor = workspaceConfig.get('thinkcalc.color', defaultColor); // 获取特定工作区设置项的值
let newColor: string | undefined;
export function activate(context: vscode.ExtensionContext) {
	const disposables: vscode.Disposable[] = [];
	//定义命令
	const thincalcstart = vscode.commands.registerCommand('extension.thincalcstart', () => {
		activaExtend(vscode);
	});
	disposables.push(thincalcstart);
	context.subscriptions.push(...disposables);
	// 注册事件监听器，监听文本编辑器的选择变化
	vscode.window.onDidChangeTextEditorSelection((event) => {

		// 获取当前活动的编辑器
		const activeTextEditor = vscode.window.activeTextEditor;
		if (activeTextEditor) {
			const textEditorCnt = vscode.window.visibleTextEditors.length;
			createDecoration(textEditorCnt);
			// 获取当前选择的文本
			const selectedText = activeTextEditor.document.getText(activeTextEditor.selection);
			// 如果选择的文本不为空，则触发 extension.selectText 命令
			if (selectedText) {
				// 遍历所有可见的文本编辑器
				vscode.window.visibleTextEditors.forEach((editor, idx) => {
					// 如果不是当前激活的编辑器

					if (editor !== activeTextEditor) {
						// 调用封装的函数进行搜索匹配和高亮操作
						highlightAllMatchingText(selectedText, editor, decorations[idx]);
					}
				});
			}
		}
	});
	vscode.workspace.onDidChangeConfiguration(e => {
		if (e.affectsConfiguration('thinkcalc.color')) {
			newColor = vscode.workspace.getConfiguration().get('thinkcalc.color');
		}
	});
}

function createDecoration(idx: number): void {
	decorations.forEach((ele) => {
		ele.dispose();
	});
	for (let i = 0; i < idx; i++) {
		const color = newColor == '' || newColor == undefined ? highlightColor : newColor;
		decorations[i] = vscode.window.createTextEditorDecorationType({
			backgroundColor: color, // 根据需要修改颜色
		});

	}
}
// 封装搜索、匹配和高亮文本的函数
function highlightAllMatchingText(selectedText: string, editor: vscode.TextEditor, decoration: vscode.TextEditorDecorationType) {
	const editorText = editor.document.getText();
	let startIndex = 0;
	const ranges: vscode.Range[] = [];

	// 循环查找所有匹配项
	while (startIndex < editorText.length && startIndex !== -1) {
		startIndex = editorText.indexOf(selectedText, startIndex);
		if (startIndex !== -1) {
			const range = new vscode.Range(
				editor.document.positionAt(startIndex),
				editor.document.positionAt(startIndex + selectedText.length)
			);
			ranges.push(range);
			startIndex += selectedText.length; // 将 startIndex 向前移动，避免再次找到相同的匹配项
		}
	}
	// 使用指定的颜色高亮所有匹配项
	editor.setDecorations(decoration, ranges);
}

async function activaExtend(vscode: typeof import('vscode')) {
	return;
}